using System;
using System.Collections.Generic;
using System.Text;

namespace Deepcode.Flux.Core.Services.XML
{
	/// <summary>
	/// Implements a Key/Value collection with Xml Serialisation and Deserialisation
	/// </summary>
	public class PropertyBag : System.Collections.ArrayList
	{
		#region Construction
		/// <summary>
		/// Constructs a new empty property bag
		/// </summary>
		public PropertyBag()
		{
		}
		/// <summary>
		/// Constructs a property bag and loads the pairs from the Xml data specified.
		/// </summary>
		/// <param name="XmlData"></param>
		public PropertyBag(string XmlData)
		{
			// Only do anything if we have data
			if (XmlData == "") return;
			// Create a new document and parse the data
			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			try { doc.LoadXml(XmlData); }
			catch { return; }
			// Clear any entries
			this.Clear();
			// Add each entry to the list
			foreach (System.Xml.XmlNode node in doc.DocumentElement.ChildNodes)
				Add(node.Name, node.InnerText);
		}
		#endregion
		#region Add/Get
		/// <summary>
		/// Adds a key/value pair to the property bag
		/// </summary>
		/// <param name="Key"></param>
		/// <param name="Value"></param>
		/// <returns></returns>
		public int Add(string Key, string Value)
		{
			PropertyBagEntry pbe = new PropertyBagEntry();
			pbe.Key = Key;
			pbe.Value = Value;
			return this.Add(pbe);
		}
		/// <summary>
		/// Retrieves a key from the property bag, or if the key doesn't exist, returns the default specified
		/// </summary>
		/// <param name="Key"></param>
		/// <param name="Default"></param>
		/// <returns></returns>
		public string Get(string Key, string Default)
		{
			foreach (PropertyBagEntry pbe in this)
				if (pbe.Key == Key) return pbe.Value;
			return Default;
		}
		#endregion
		#region Serialisation
		/// <summary>
		/// Serialise the property bag name/value pairs to an XML string
		/// </summary>
		/// <returns></returns>
		public string Serialise()
		{
			// Create a new document
			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			// Create the root <Config> tag
			System.Xml.XmlNode root = doc.CreateElement("Config");
			doc.AppendChild(root);
			// Enumerate all the property bag entries
			foreach (PropertyBagEntry pbe in this)
			{
				// Create an xml node as required and set it's value
				System.Xml.XmlNode node = doc.CreateElement(pbe.Key);
				node.InnerText = pbe.Value;
				root.AppendChild(node);
			}
			// Convert the XML document to a string
			return doc.OuterXml;
		}
		#endregion
	}
}
